package com.nd.android.u.ui.activity.message_chat;

import ims.utils.IMLogUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.common.StarAppConst;
import com.common.android.utils.smiley.Smiley;
import com.common.android.utils.smiley.Smileyhelper;
import com.common.android.utils.task.genericTask.GenericTask;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.controller.ChatConst.KEY;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.ChatGlobalVariable;
import com.nd.android.u.controller.factory.DataSupplierFactory;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IMessageObserver;
import com.nd.android.u.controller.innerInterface.IUIDataSupplier;
import com.nd.android.u.controller.observer.MessageDispatcher;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.chatUiUtils.AudioQuenePlayManager;
import com.nd.android.u.ui.chatUiUtils.LocalImageManager;
import com.nd.android.u.ui.chatUiUtils.SendMessageUtil;
import com.nd.android.u.ui.chatUiUtils.UnSendMessageManager;
import com.nd.android.u.ui.widge.PopAudioModeNotice;
import com.nd.android.u.ui.widge.ResizeLayout;
import com.nd.android.u.ui.widge.chatfragment.BottomFragment;
import com.nd.android.u.ui.widge.chatfragment.BottomFragment.OnBottomDlgChange;
import com.nd.android.u.ui.widge.chatfragment.MessageListFragment;
import com.nd.android.u.ui.widge.chatfragment.MessageListFragment.MessageListListener;
import com.nd.android.u.ui.widge.chatfragment.PopQuickReply;
import com.nd.android.u.ui.widge.chatfragment.PopQuickReply.onItemSelectListener;
import com.product.android.ui.activity.BaseFragmentActivity;

public abstract class BaseChatMessageActivity extends BaseFragmentActivity 
implements MessageListListener, IUIDataSupplierGetter {
	// protected static final int HEAD_CONTAINER_ID = R.id.head_container;
	protected static final int CONTENT_CONTAINER_ID = R.id.content_container;
	protected static final int BOTTOM_CONTAINER_ID = R.id.bottom_container;
	// protected static final int CONTENT_FLOWER = R.id.content_flower;
	protected static final int PSP_BOTTOM_CONTAINER_ID = R.id.psp_bottom_container;
	/** 界面头部 */
	protected CommonActivityTitle mActivityTitle;
	// protected HeadFragment mheadFragment; XXX 无HeadFragment
	/** 消息列表 */
	protected MessageListFragment mMessageListFragment;
	/** 界面底部 */
	protected BottomFragment mBottomFragment;
	/** 有菜单的界面底部 */
	// protected PspBottomFragment mpubNumBottomFragment; XXX 无PspBottomFragment
	/** 鲜花插件 */
	// protected FlowerFragment mflowerFragment;XXX 无FlowerFragment
	/** 主的Layout */
	protected ResizeLayout msgLayout;
	/** 快速回复窗口相关 */
	protected String[] mPostQuickReplies;
	protected PopQuickReply mPopQuickReply;
	protected int mQuickReplyType;
	protected ProgressDialog waitDialog;
	protected GenericTask copyAcknowledgeAudioTask;

	protected static final int BIGGER = 3;
	protected static final int SMALLER = 4;
	/** 是否隐藏表情控件 */
	protected boolean showSimley = false;
	/** 扬声器与听筒转换通知 */
	protected PopAudioModeNotice mAudioModeNotice;
	/** 通用id（个人消息 ：uid，群消息：gid,应用消息:appid,公众号消息：pspid) */
	protected long generalId;
	/** 应用消息的code */
	protected String appcode;
	/** 群的类型 */
	protected int groupType;
	/** 转发消息的generateid */
	protected String repostMsgId;
	/** 在此次重构中区分区分各种消息 */
	protected int messageType;
	/** 当前聊天对象的名称 */
	protected String name;
	/** 数据提供者 */
	private IUIDataSupplier mDataSupplier;

	/**
	 * 上下文
	 */
	protected Activity mActivity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_chat);
		mActivity=this;
		Bundle bundle = getIntent().getExtras();
		if (bundle == null) {
			finish();
			return;
		}
		name = bundle.getString(KEY.NAME);
		if (!getParam(bundle)) {
			finish();
			return;
		}
		initDataSupplier();
		if (mDataSupplier == null) {
			IMLogUtils.e(IMLogUtils.CHAT, "null data supplier:" + messageType + ",id=" + generalId + ",grouptype=" + groupType + ",appcode="
					+ appcode);
			finish();
		}
		addDefaultFragment();
		initEvent();
		specialProccess();
	}

	/**
	 * 默认的右上角的按钮背景资源 <br>
	 * Created 2014-8-4 下午1:46:08
	 * 
	 * @return 右上角的按钮背景资源
	 * @author cb
	 */
	protected int getRightButtonRes() {
		return R.drawable.common_activity_title_btn_friend;
	};

	/**
	 * 一些子类特殊的处理 <br>
	 * Created 2014-8-2 上午11:29:00
	 * 
	 * @author cb
	 */
	protected void specialProccess() {
	};

	/**
	 * 获取id/type/code等参数 <br>
	 * Created 2014-7-29 下午12:14:41
	 * 
	 * @param bundle
	 * @return false:获取参数异常，结束当前界面
	 * @author cb
	 */
	protected abstract boolean getParam(Bundle bundle);

	/**
	 * 添加默认的fragment <br>
	 * Created 2014-7-26 下午4:16:23
	 * 
	 * @author cb
	 */
	protected void addDefaultFragment() {
		// 界面头部
		initTitleView();
		// 界面中间消息列表
		initMessageListView();
	}
	
	/**
	 * 初始化界面头部
	 * <br>Created 2014-9-22 下午9:42:47
	 * @author  cb
	*/
	private void initTitleView(){
		mActivityTitle = (CommonActivityTitle) findViewById(R.id.common_chat_title);
		mActivityTitle.setTitleTextTypeface(StarAppConst.getInstance().getLTXTypeface(), true);
		mActivityTitle.showRightBtn();
		mActivityTitle.showLeftBtn();
		mActivityTitle.setRightBtnBackground(getRightButtonRes());
		mActivityTitle.hideNewMsgTip();
		mActivityTitle.setTitleBtnCallback(mTitleBtnCallback);
		mActivityTitle.setTitleText(name);
	}
	
	/**
	 * 初始化消息列表控件
	 * <br>Created 2014-9-20 上午11:56:14
	 * @author  cb
	*/
	private void initMessageListView(){
		if (mMessageListFragment==null){
			mMessageListFragment = new MessageListFragment(this);
			mMessageListFragment.setDataSupplier(mDataSupplier);
			mMessageListFragment.setMessageListListener(this);
			mMessageListFragment.setMessageType(messageType);
			mMessageListFragment.setRepostId(repostMsgId);
			ViewGroup container=(ViewGroup) findViewById(CONTENT_CONTAINER_ID);
			container.addView(mMessageListFragment);
		}else{
			mMessageListFragment.setDataSupplier(mDataSupplier);
			mMessageListFragment.setMessageType(messageType);
			mMessageListFragment.setRepostId(repostMsgId);
		}
	}

	@Override
    public void onStart() {
        super.onStart();
        ChatGlobalVariable.getInstance().isOpenCamera = false;
        MessageDispatcher.getInstance().registAllObserver(LocalMessageType.class, observer);
     // 恢复未发送的消息
        if (mBottomFragment!=null){
        	String lastUnsendMessage = UnSendMessageManager.INSTANCE.getUnsendMessage(generalId);
     		if (!TextUtils.isEmpty(lastUnsendMessage)) {
     			SpannableString string = Smileyhelper.getInstance().getSmileySpannableString(lastUnsendMessage, Smiley.TYPE_CHAT);
     			mBottomFragment.getContentEdit().setText(string);
     			mBottomFragment.getContentEdit().requestFocus();
     			mBottomFragment.getContentEdit().setSelection(string.length());
     		}
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        AudioQuenePlayManager.getInstance().stopPlayAndSetCureentNull();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	ChatGlobalVariable.getInstance().dataSupplier=mDataSupplier;
        if (mPopQuickReply!=null){
        	mPopQuickReply.refresh();
        }
    }
    
    /**
     * 重绘view <br>
     * Created 2014-7-18 下午2:31:53
     * 
     * @param intent
     * @author mengnan
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle newBundle = intent.getExtras();
        if(newBundle!=null){
        	if (!getParam(newBundle)){
        		finish();
        		return;
        	}
            initDataSupplier();
            if (mDataSupplier==null){
            	finish();
            	return;
            }
            addDefaultFragment();
        }
    }

	/**
	 * 初始化底部控件
	 * <br>Created 2014-9-20 下午12:49:41
	 * @author  cb
	*/
	protected void initBottomView(){
		if (mBottomFragment==null){
			mBottomFragment=new BottomFragment(this);
			ViewGroup group=(ViewGroup) findViewById(BOTTOM_CONTAINER_ID);
			group.addView(mBottomFragment);
			mBottomFragment.setOnBottomDlgChange(new OnBottomDlgChange() {

				@Override
				public void onBottomDlgChange() {
					// TODO Auto-generated method stub
					if (mMessageListFragment != null) {
						mMessageListFragment.scrollToBottom(false);
					}
				}
			});
			
		}
		mBottomFragment.setMessageType(messageType);
		/** 弹窗页面进来时传过来的消息内容（编辑框里的），只有群和个人有用 */
        if (getIntent().hasExtra("content")) {
            String content = getIntent().getStringExtra("content");
            if (!TextUtils.isEmpty(content)){
    			mBottomFragment.setEditTextValue(content);
    		}
        }
		mBottomFragment.setDataSupplier(mDataSupplier);
		if (messageType == LocalMessageType.GROUP){
			mBottomFragment.setGroupType(groupType);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mMessageListFragment.clearData();
		LocalImageManager.INSTANCE.clear(this);
	}
	
	@Override
	public void finish() {
		super.finish();
		ChatGlobalVariable.getInstance().dataSupplier=null;
		mMessageListFragment.clearData();
		MessageDispatcher.getInstance().unregistAllObserver(LocalMessageType.class, observer);
		if (mBottomFragment!=null){
			String unsendMessage = mBottomFragment.getContentEdit().getText().toString();
			UnSendMessageManager.INSTANCE.put(generalId, unsendMessage);	
		}
	}

	// 快速回复窗口开始
	/**
	 * 创建快速回复 <br>
	 * Created 2014-7-18 下午2:34:39
	 * 
	 * @param fid
	 *            fid
	 * @author mengnan
	 */
	protected void createPopQuickReply(long fid) {
		if (mPopQuickReply == null || mPopQuickReply.getmReplyType() != mQuickReplyType) {
			mPopQuickReply = new PopQuickReply(this, mQuickReplyType, fid);
			if (mPostQuickReplies != null && mQuickReplyType == PopQuickReply.REPLY_TYPE_PRESENT) {
				mPopQuickReply.setQuickReply(mPostQuickReplies);
			}
			mPopQuickReply.setOnItemSelectListener(new onItemSelectListener() {
				@Override
				public void onItemSelect(String text) {
					SendMessageUtil.sendMessage(MessageContentType.TEXT, text, null, 0,mDataSupplier);
				}
			});
		}
	}

	@Override
	public void onDismissOtherFragment() {
		// 系统消息、应用消息没有Bottomfragment
		if (null != mBottomFragment) {
			mBottomFragment.dismisswidge();
		}
	}

	@Override
	public IUIDataSupplier getDataSupplier() {
		return mDataSupplier;
	}

	public void leftBtnHandle() {
		if(mBottomFragment!=null){
			mBottomFragment.hideSoftInput(mBottomFragment.getContentEdit());
		}
		finish();
	}

	public void rightBtnHandle() {
		// 子类自己实现
	}

	private TitleBtnCallback mTitleBtnCallback = new TitleBtnCallback() {
		@Override
		public void onBtnClick(int clickType) {
			switch (clickType) {
			case CommonActivityTitle.ON_LEFT_CLICK_CALL_BACK:
				leftBtnHandle();
				break;
			case CommonActivityTitle.ON_RIGHT_CLICK_CALL_BACK:
				rightBtnHandle();
				break;
			default:
				break;
			}
		}
	};
	
	private IMessageObserver observer=new IMessageObserver() {
		@Override
		public void onSendNewMessage(IMessageDisplay message) {
			
		}
		
		@Override
		public void onReceiveMessage(IMessageDisplay message) {
			int type=message.getMessageType();
			if (type==messageType){
				//当前界面需要处理的消息
				if (mDataSupplier.isValidMessage(message)){
					return;
				}
			}
			int[] sonTypes=ChatInterfaceImpl.INSTANCE.getSubTypes(messageType);
			if (sonTypes!=null){
				for (int i : sonTypes) {
					if (i==type){
						//子类型是当前界面要处理的
						return;
					}
				}
			}
			//显示小红点
			runOnUiThread(new Runnable() {
				public void run() {
					mActivityTitle.showNewMsgTip();		
				}
			});
			//解注册所有的观察者，因为再收到新消息也不会有任何改变
			MessageDispatcher.getInstance().unregistAllObserver(LocalMessageType.class, observer);
		}
		
		@Override
		public void onOtherMessageNotify(Message message) {
			processOtherMessageNotify(message);
		}
		
		@Override
		public void onMessageStateChanged(IMessageDisplay message, int state) {
			
		}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (mBottomFragment!=null){
			mBottomFragment.onActivityResult(requestCode, resultCode, data);
		}
	};
	
	@Override
	public void onBackPressed() {
		if (mBottomFragment!=null){
			mBottomFragment.hideSoftInput(mBottomFragment.getContentEdit());
			
			if (mBottomFragment.hideSmileyViewAndAppGrid()){
				return;
			}
			
		}
		super.onBackPressed();
	};
	
	protected void processOtherMessageNotify(Message message){
	    ;
	}
	
	/**
     * @函数名称  :initDataSupplier
     * @brief 初始化数据提供者
     * @see
     * @author  : cb
     * @date  : 2014-11-30 02-36-37
     */
    private void initDataSupplier(){
        mDataSupplier = DataSupplierFactory.INSTANCE.getDataSupplier(messageType, generalId, groupType,appcode);
        if (mDataSupplier==null){
            return;
        }
        mDataSupplier.clearUnreadCount();
        IMessageDisplay message = mDataSupplier.getConcreteMessage();
        message.getProccessInterface().ackAllMessage();
    }
}
